<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB2312"/>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scaleable=no"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <title>微信蓝牙定位</title>

    <!--// ============= WeiXin ===================-->
    <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>css/wap-style.css?t=asd"/>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>js/wapAlert.css"/>
    <script type="text/javascript" src="<%=basePath%>js/wapAlert.js"></script>
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript">
        var beaconArray;
        var locationEngine;
        var currentLocation;
        var autoSwitch = true;
        var isDebugEnable = false;
        var isSignalShow = false;
    </script>

    <script type="text/javascript">
        function getParameter(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
        function callback(evt) {
            console.log("jsonpcallback");
            initWeiXin(evt);
        }

        var appidUser = getParameter("appidUser");
        if (!appidUser) {
            appidUser = "BrtBeacon";
        }


        if (getParameter("debug")) {
            isDebugEnable = true;
        }
        isDebugEnable = true;

        if (getParameter("signal")) {
            isSignalShow = true;
        }

        /*var scriptSource = "http://platalk.cn/TYWeiXinSignature/WeiXinSignature?wxuser=" + appidUser + "&wxcallback=callback&wxurl=" + window.location.href;
        //    var scriptSource = "http://platalk.cn/TYWeiXinSignature/WeiXinSignature?wxuser=BrtBeacon&wxcallback=callback&wxurl="+ window.location.href;
        var script = document.createElement("script");
        script.setAttribute("src", scriptSource);
        document.getElementsByTagName("head")[0].appendChild(script);*/

        initWeiXin();
        function initWeiXin() {
            console.log("initWeiXin");
            wx.config({
                debug: false,
                appId: '${signmap.appId}',
                timestamp: ${signmap.timestamp},
                nonceStr: '${signmap.nonceStr}',
                signature: '${signmap.signature}',
                jsApiList: [
                    'checkJsApi',
                    'startMonitoringBeacons',
                    'stopMonitoringBeacons',
                    'onBeaconsInRange',
                    'startSearchBeacons'
                ]
            });

            wx.ready(function () {
                wx.startSearchBeacons({
                    ticket: "",
                    complete: function (argv) {
                        //回调函数
                    }
                });

                var index = 0;

                wx.onSearchBeacons({
                    complete: function (argv) {
                        index++;
                        var scannedBeaconArray = new Array();
                        for (var beaconIndex = 0; beaconIndex < argv.beacons.length; beaconIndex++) {
                            var beacon = argv.beacons[beaconIndex];
                            if (beacon.rssi < -15) {
                                scannedBeaconArray.push(beacon);
                            }
                        }
                        if (isSignalShow) {
                            map.showScannedBeacons(beaconArray, scannedBeaconArray);
                        }

                        locationEngine.didRangeBeacons(scannedBeaconArray);

                        var resultLocation = locationEngine.getLocation();
                        currentLocation = resultLocation;
                        startButtonClicked();

                        if (resultLocation != null) {
                            if (autoSwitch) {
                                if (resultLocation.floor != currentMapInfo.floorNumber) {
                                    var needSwitch = false;
                                    for (var i = 0; i < allMapInfoArray.length; ++i) {
                                        if (allMapInfoArray[i].floorNumber == resultLocation.floor) {
                                            currentMapInfo = allMapInfoArray[i];
                                            needSwitch = true;
                                            break;
                                        }
                                    }
                                    if (currentMapInfo) {
                                        showMapInfo(currentMapInfo);
                                    }
                                }
                            }
                            map.showLocation(resultLocation);
                        } else {
                            map.showLocation(null);
                        }
                    }
                });

                wx.error(function (res) {
                    console.log(res.errMsg);
                });
            });
        }

    </script>


</head>

<body class="claro">
<div class="mapManager">
    <div id="map" class="mapview">
    </div>


    <div id="positioningDiv" class="positioningDiv">
        <!--取消导航按钮-->
        <img id="clearRecord" src="<%=basePath%>img/clear.png" height="35px" style="display:none;"/>
        <!--找出按钮-->
        <img id="findRecord" src="<%=basePath%>img/find-car.png" height="35px" style="display:none;"/>
    </div>

    <div class="position-me-module" style="position: absolute; bottom: 15px; right: 15px;">
        <!--地图右下角定位按钮-->
        <img src="http://map.brtbeacon.com/TYMap/image/positioning_button.png" width="50px" onclick="positionButtonClicked()"/>
    </div>

    <div id="UI" class="ui">
        <div id="floorListDiv" class="floorListDiv">
        </div>
        <div style="width: 200px;margin: 0 auto; display: none;">
            <button id="switchFloorButton" class="floorbutton" onclick="floorButtonClicked()"></button>
        </div>
    </div>

    <div class="point-icon" style=" display: none;">
        <!--停车提示框-->
        <div class="cog-point-module">
            <div class="title">提示</div>
            <div id="car-tips" class="info">您是否确定停车？</div>

            <div class="btn-box">
                <a class="off">取消</a>
                <a class="yes">确定</a>
            </div>
        </div>

    </div>
</div>

<!--<script src="/TYMap/js/tymap-1.1.js"></script>-->
<script src="http://platalk.cn/TYMap/js-1.1/tymap-1.1.js"></script>

<script type="text/javascript">
    var cbm;
    var map;
    var city, building, allMapInfoArray, currentMapInfo;
    var currentClickPoint, currentStartPoint, currentEndPoint;
    var routeManager;
    var isRouting;

    var requestRoute;
    var floorItemClicked;

    /**公众号ID**/
    var appid = "${appid}";
    /**微信ID**/
    var openid ="${openid}";
    /**起点X坐标**/
    var spointX;
    /**起点Y坐标**/
    var spointY;
    /**终点X坐标**/
    var epointX;
    /**终点Y坐标**/
    var epointY;
    /**是否是点击获取定位**/
    var isAjax = false;
    /**终点停车描述**/
    var endPointName="";



    // 改动1 - 开始
    //  声明标注层，require相应类，声明添加标注层方法和添加标注的方法
    var annotationLayer;
    var addAnnotationLayer;
    var showAnnotations;
    require([
        "esri/layers/GraphicsLayer",
        "esri/graphic",
        "esri/symbols/PictureMarkerSymbol",
        "dojo/domReady!"], function (GraphicsLayer, Graphic, PictureMarkerSymbol) {
        annotationLayer = new GraphicsLayer();

        addAnnotationLayer = function () {
            console.log("addAnnotionaLayer");
            map.addLayer(annotationLayer);
        };

        showAnnotations = function (point) {
            console.log("showAnnotaions");
            annotationLayer.clear();

            var imageSymbol = new PictureMarkerSymbol("<%=basePath%>img/route_end_point.png", 33, 43).setOffset(0, 22);
            console.log(imageSymbol);
            annotationLayer.add(new Graphic(point, imageSymbol));
        };
    });
    // 改动1 - 结束

    TYMapEnvironment.ready = function () {
        console.log("TYMapEnvironment.ready");
        cityID = getParameter("city");
        buildingID = getParameter("building");

        if (!cityID || !buildingID) {
            cityID = "0021";
            buildingID = "00210029";
        }

        map = new TYMapView("map", {
            logo: false
        });

        cbm = new TYCBMParser();
        cbm.didFinishParsingCBM = function (data) {
            console.log("didFinishParsingCBM");
            city = data.city;
            building = data.building;
            allMapInfoArray = data.mapInfos;
            currentMapInfo = allMapInfoArray[0];
            map.initMapView(building);

            routeManager = new TYRouteManager(building, allMapInfoArray);
            routeManager.didSolvedRouteCallback = function (result) {
                console.log("routeManager.didSolvedRouteCallback");
                console.log(result);


                map.setRouteResult(result);
                map.showRouteOnCurrentFloor();
            };
            routeManager.didFailedSolvedRouteCallback = function () {
                wapAlert("没有找到合适路径");
                map.hideRoute();
            };
            console.log("requestBeacons");
            requestBeacons();
        };
        cbm.parseCBM(getCBMPathCO("cbm", buildingID));

        map.infoWindow.resize(160, 200);
        /**定位图标**/
        var infoHtml = '<img src="http://map.brtbeacon.com/TYMap/image/route_end_button.png" onclick="endButtonClicked();"/> <img src="<%=basePath%>img/route_cancel_button.png" onclick="closeTip();"/>';
        map.infoWindow.setContent(infoHtml);


        map.didFinishLoadingFloor = function (mapInfo) {
            if (isRouting) {
                map.showRouteOnCurrentFloor();
            }
        };

        map.didFinishInitMapView = function (data) {

//      改动2 - 开始
//      在地图初始化完成后，添加标注层
            addAnnotationLayer();
//改动2 - 结束

            if (allMapInfoArray.length > 0) {
                initFloorUI(allMapInfoArray);
                currentMapInfo = allMapInfoArray[0];
                showMapInfo(currentMapInfo);
            }
            map.setFloorWithInfo(currentMapInfo);
            //隐藏默认的放大缩小
            map.hideZoomSlider();
        };

        /**连接起点与重点的连接线**/
        requestRoute = function () {
            if (currentStartPoint == null || currentEndPoint == null) {
                return;
            }

            isRouting = true;

            console.log('currentStartPoint',currentStartPoint);
            console.log('currentEndPoint',currentEndPoint);
            routeManager.requestRoute(currentStartPoint, currentEndPoint);
        };

        map.on("click", function (evt) {
            currentClickPoint = evt.mapPoint;
            console.log(evt.mapPoint);

//      改动3 - 开始
//      在标注层上显示标注，此处放在点击回调函数内，仅用于测试。
//      根据需求，可以放在实现相应逻辑的方法中
            showAnnotations(evt.mapPoint);
//改动3 - 结束

            var graphic = map.extractPOI(evt.mapPoint);
            if (graphic != null) {
                if (graphic.attributes["NAME"] != null) {
                    if (graphic.attributes["NAME"] != null && graphic.attributes["NAME"].length > 0) {
                        $("#car-tips").html("您是否确定在"+graphic.attributes["NAME"]+"停车？");
                        endPointName = graphic.attributes["NAME"];
                        //定位车位坐标名称
                        map.infoWindow.setTitle(graphic.attributes["NAME"]);
                        currentClickPoint.x = graphic.attributes["LABEL_X"];
                        currentClickPoint.y = graphic.attributes["LABEL_Y"];
                    }
                }
                clickShow();
                //map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
            } else {
                map.infoWindow.hide();
            }
        });

        var requestBeacons = function () {
            window._define = function(result) {
                console.log(result);
                var beaconArray = [];
                var publicBeaconArray = result.beacons;
                for (var i = 0; i < publicBeaconArray.length; ++i) {
                    var pb = new TYPublicBeacon();
                    pb.parsePublicBeaconNode(publicBeaconArray[i]);
                    beaconArray.push(pb);
                }
                locationEngine = new TYLocationEngine();
                locationEngine.loadBeacons(beaconArray);
            };

            require([ 'http://map.brtbeacon.com/TYMapServerManager/wx/QueryLocatingBeacons?buildingID=' + building.buildingID + '&callback=_define' ], function(a) {

            });
        }
//        setTimeout(function(){
//            startButtonClicked();
//        },3000);
    };
    TYMapEnvironment.init();


</script>

<script type="text/javascript">

    $(function(){

        /**取消导航按钮事件**/
        $("#clearRecord").on("click",function(){
                map.hideRoute();//隐藏线路
                $("#clearRecord").hide();//隐藏取消导航按钮
                $("#findRecord").show();//显示找出按钮
                startButtonClicked();
                map.showEndPoint(currentEndPoint);//显示终点锚点
                <%--$.ajax({--%>
                    <%--url:'<%=basePath%>reverse/delete',--%>
                    <%--type:'POST',--%>
                    <%--dataType:'json',--%>
                    <%--data:{--%>
                        <%--appid:appid,--%>
                        <%--openid:openid--%>
                    <%--},--%>
                    <%--success:function(data){--%>
                        <%--if(data.code == 1){--%>
                            <%--map.hideRoute();--%>
                            <%--$("#clearRecord").hide();--%>
                            <%--$("#findRecord").show();--%>
                            <%--startButtonClicked();--%>
                            <%--map.showEndPoint(currentEndPoint);//显示终点锚点--%>
                        <%--}else if(data.code ==-1){--%>
                        <%--}--%>
                    <%--}--%>
                <%--});--%>
        });


        /**点击查找车辆方法**/
        $("#findRecord").on("click",function(){
            if(isAjax){
                if (currentEndPoint != null && currentStartPoint != null) {
                    $("#findRecord").hide();
                    $("#clearRecord").show();
                    //判断终点是否定位，如果存在则连接线路
                    requestRoute();
                }else{
                    $.ajax({
                        //请求后台地址
                        url:'<%=basePath%>reverse/find',
                        type:'POST',
                        dataType:'json',
                        data:{
                            appid:appid,
                            openid:openid
                        },
                        success:function(data){
                            if(data.code == 1){
                                spointX = data.data.spointX;
                                spointY = data.data.spointY;
                                epointX = data.data.epointX;
                                epointY = data.data.epointY;
                                route();
                                $("#findRecord").hide();
                                $("#clearRecord").show();
                            }
                        }
                    });
                }
            }else{
                wapAlert("您没有在停车场区域，无法查找到您的车！");
            }
        });

    });

    /**找车车辆**/
    <%--function searchEndPoint(){--%>
        <%--//获取搜索文本框的值--%>
        <%--var searchText = $("#searchText").val();--%>
        <%--//判断文本框的信息--%>
        <%--if(searchText != null && searchText != ""){--%>
            <%--$.ajax({--%>
                <%--url:'<%=basePath%>reverse/search',--%>
                <%--type:'POST',--%>
                <%--dataType:'json',--%>
                <%--data:{--%>
                    <%--searchText:searchText--%>
                <%--},--%>
                <%--success:function(data){--%>

                <%--}--%>
            <%--});--%>
        <%--}else{--%>
            <%--wapAlert("搜索信息不能为空！");--%>
        <%--}--%>
    <%--}--%>

    <%--/**找车按钮**/--%>
    function findEndPoint(){
        $.ajax({
            //请求后台地址
            url:'<%=basePath%>reverse/find',
            type:'POST',
            dataType:'json',
            data:{
                appid:appid,
                openid:openid
            },
            success:function(data){
                if(data.code == 1){
                    //终点位置
                    epointX = data.data.epointX;
                    //起点位置
                    epointY = data.data.epointY;
                    //隐藏取消导航
                    $("#clearRecord").hide();
                    //隐藏找车
                    $("#findRecord").show();
                    if(epointX != null && epointX !="" && epointY != null && epointY !=""){
                        //初始化终点坐标
                        currentEndPoint = new TYLocalPoint(epointX, epointY, -2);
                        //显示终点锚点
                        map.showEndPoint(currentEndPoint);
                    }
                }
            }
        });
    }

    /**连线操作**/
    function route(){
        map.infoWindow.hide();//隐藏停车显示框
        if(spointX!= null && spointX !="" && spointY != null && spointY !="" && epointX != null && epointX !="" && epointY != null && epointY !=""){
            //初始化起点坐标对象
            currentStartPoint = new TYLocalPoint(spointX, spointY, -2);
            //初始化终点坐标对象
            currentEndPoint = new TYLocalPoint(epointX, epointY, -2);
            //显示起点锚点
            map.showStartPoint(currentStartPoint);
            //显示终点锚点
            map.showEndPoint(currentEndPoint);
        }
        if (currentEndPoint != null && currentStartPoint != null) {
            requestRoute();//判断终点是否定位，如果存在则连接线路
        }
    }

    /**定位起点坐标**/
    function startButtonClicked() {
        //隐藏停车显示框
        map.infoWindow.hide();
        if(currentLocation != null){
            //初始化起点坐标对象
            currentStartPoint = new TYLocalPoint(currentLocation.x, currentLocation.y, -2);
            //显示起点锚点
            map.showStartPoint(currentStartPoint);
            if(currentEndPoint == null){
                //如果起点为空，则查找上一次停车地点
                findEndPoint();
            }
            isAjax = true;
        }

        annotationLayer.clear();//清楚悬浮定位图标
    }

    /**关闭点击显示层**/
    function closeTip(){
        annotationLayer.clear();
        map.infoWindow.hide();
    }

    /**定位终点坐标**/
    function endButtonClicked() {
        map.hideEndPoint();
        //重写终点定位图标，参数(图片路径，宽度，搞得，横向偏移量，纵向偏移量)
        map.setRouteEndSymbol("<%=basePath%>img/route_end_point.png", 32, 43, 0, 20);
        if(currentStartPoint != null && currentEndPoint != null){
            map.hideRoute();
        }
        //隐藏点击框
        map.infoWindow.hide();
        /***创建终点坐标对象*/
        currentEndPoint = new TYLocalPoint(currentClickPoint.x, currentClickPoint.y, currentMapInfo.floorNumber);
        //显示起点锚点
        map.showStartPoint(currentStartPoint);
        //显示终点锚点
        map.showEndPoint(currentEndPoint);

        if (currentStartPoint == null && currentLocation != null) {
            currentStartPoint = currentLocation;
        }
        //隐藏清楚按钮
        $("#clearRecord").hide();
        //显示找出按钮
        $("#ecord").show();
        if(currentStartPoint != null && currentEndPoint != null){
            var params_ = {
                appid:appid,//公众号ID
                openid:openid,//微信ID
                startname:'',
                spointX:currentStartPoint.x,//起点X坐标
                spointY:currentStartPoint.y,//起点Y坐标
                endname:endPointName,
                epointX:currentClickPoint.x,//终点X坐标
                epointY:currentClickPoint.y,//终点Y坐标
                cityId:cityID,//成熟ID
                buildingId:buildingID
            }
            $.ajax({
                url:'<%=basePath%>reverse/save',
                type:'POST',
                dataType:'json',
                data:params_,
                success:function(data){
                }
            });
        }

        annotationLayer.clear();
    }

    function initFloorUI(mapInfoArray) {
        var mapInfoHTML = "<ui>";
        for (var i = 0; i < mapInfoArray.length; ++i) {
            var mapInfo = mapInfoArray[i];
            var html = "<li class='floorItem'><button class='floorItem' id='" + mapInfo.mapID + "' onclick='floorItemClicked(this);return false;'>" + mapInfo.floorName +
                    "</button>";
            mapInfoHTML += html;
        }
        mapInfoHTML += "</ui>";
        document.getElementById("floorListDiv").innerHTML = mapInfoHTML;
    }

    floorItemClicked = function (floorButton) {
        hideSwitchFloorDiv();
        autoSwitch = false;

        for (var i = 0; i < allMapInfoArray.length; ++i) {
            if (allMapInfoArray[i].mapID == floorButton.id) {
                currentMapInfo = allMapInfoArray[i];
                break;
            }
        }
        if (currentMapInfo) {
            showMapInfo(currentMapInfo);
        }
    };

    function showMapInfo(mapinfo) {
        map.setFloorWithInfo(mapinfo);
        document.getElementById("switchFloorButton").innerHTML = mapinfo.floorName;
    }
</script>

<script type="text/javascript">
    var isShown = false;
    var switchFloorDiv = document.getElementById("floorListDiv");
    function floorButtonClicked() {
        if (!switchFloorDiv) {
            switchFloorDiv = document.getElementById("floorListDiv");
        }
        if (isShown) {
            hideSwitchFloorDiv();
        } else {
            showSwitchFloorDiv();
        }
    }

    function positionButtonClicked() {
        autoSwitch = true;
    }


    function showSwitchFloorDiv() {
        if (!isShown) {
            switchFloorDiv.style.visibility = "visible";
            isShown = true;
            for (var i = 0; i < allMapInfoArray.length; ++i) {
                var mapInfo = allMapInfoArray[i];

                if (currentMapInfo && currentMapInfo.mapID == mapInfo.mapID) {
                    document.getElementById(mapInfo.mapID).className = "floorItemSelected";
                } else {
                    document.getElementById(mapInfo.mapID).className = "floorItem";
                }
            }
        }
    }
    function hideSwitchFloorDiv() {
        if (isShown) {
            switchFloorDiv.style.visibility = "hidden";
            isShown = false;
        }
    }

    function onMapClicked() {
        if (isShown) {
            hideSwitchFloorDiv();
        }
    }

    function onSelectFloorClicked() {

    }

    /**点击显示弹出框按钮**/
    function clickShow(){
        var h = document.documentElement.clientHeight,w=document.documentElement.clientWidth;
        $(".point-icon").show().css({
            /**设置弹出框的左边距**/
            "left":(w*0.2)+"px",
            /**设置弹出框的上边距**/
            "top":(h*0.6)+"px"
        }).find(".cog-point-module").show();
    }

    /**显示弹出框**/
    $("div.point-icon").on("click",".btn-box .off",function(e){

        $(".point-icon").hide();
        /**隐藏锚点位置**/
        closeTip();
        e.stopPropagation();

    }).on("click",".btn-box .yes",function(e){

        $("div.cog-point-module").hide();
        /**确认连接终点**/
        endButtonClicked();
        e.stopPropagation();

    });



</script>

</body>
</html>